package com.sci.handler;

import com.sci.entity.CommonResult;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(-1)
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        String message = "服务器内部错误";

        if (ex instanceof SecurityException) {
            status = HttpStatus.UNAUTHORIZED;
            message = ex.getMessage();
        }

        response.setStatusCode(status);

        CommonResult<String> result = new CommonResult<>(
                status.value(),
                message,
                null
        );

        return response.writeWith(Mono.just(response.bufferFactory()
                .wrap(result.toString().getBytes())));
    }
}